package demo05

/**
 * @author xiaoZhao
 * @date 2022/6/30
 * @describe
 */
object Test11_Object {
  def main(args: Array[String]): Unit = {
//    val student = new Student11("alice", 12)
//    student.printInfo()

    val student = Student11.newStudent("alice", 12)
    student.printInfo()

    val student1 = Student11.apply("haha", 12)

    val student2 = Student11("lolo", 34)
    student2.printInfo()
  }
}

// 伴生类
// 构造器私有化
class Student11 private(val name: String, val age: Int) {
  def printInfo(): Unit = {
    println(s"Student11: $name $age ${Student11.school}")
  }
}

// 伴生对象
object Student11 {
  // 看作静态的属性
  val school: String = "清华"
  // 定义类对象实例创建的方法
  def newStudent(name: String,age: Int): Student11 = new Student11(name,age)

  // Scala底层对于伴生对象的apply方法进行了优化，调用时可以省略方法名，直接使用单例对象的名称+调用apply方法的参数
  def apply(name: String, age: Int): Student11 = new Student11(name, age)
}